/*
* 领料单明细列表
* */

import 'dart:convert';

import 'package:center_beijing/api/material_science_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class MaterialRequisitionDetailList extends StatefulWidget {
  @override
  _MaterialRequisitionDetailListState createState() =>
      _MaterialRequisitionDetailListState();
}

class _MaterialRequisitionDetailListState
    extends State<MaterialRequisitionDetailList>
    with SingleTickerProviderStateMixin {
  EasyRefreshController _controller = EasyRefreshController();
  CustomLoading loading = CustomLoading.withMessage('请稍候...');
  var receive = Get.arguments['pass'];
  var type = Get.arguments['type'];
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;
  bool canEdit = Get.arguments['canEdit'];

  @override
  void initState() {
    super.initState();
    bus.on('refreshRequisitionDetailList', (arg) {
      page = 1;
      this.getAllReceived();
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    bus.off('refreshRequisitionDetailList');
    loading.dismiss();
    super.dispose();
  }

  /*
  * 获取领料单材料列表
  * */
  getAllReceived() async {
    var pass = {
      'queryFields': json.encode([
        {
          "columnName": 'requisitionOrderId',
          "dataType": "string",
          "operator": "=",
          "queryValue": receive['id'],
        }
      ]),
      'page': page,
      'limit': pageSize,
    };
    var result = type
        ? await getRequisitionMaterialEntryExList(pass)
        : await getRequisitionMaterialEntryExListNo(pass);
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null && result['hasError'] == null) {
      this.setState(() {
        if (result['results'].length == 0) {
          _controller.finishLoad(success: true, noMore: true);
        } else {
          dataSource.addAll(result['results']);
          if (dataSource.length == result['totalRecordNum']) {
            _controller.finishLoad(success: true, noMore: true);
          }
        }
      });
    } else {
      _controller.finishLoad(success: true);
    }
  }

  /*
  * 删除领料单详情
  * */
  deleteMaterialDetail(value) async {
    loading.show(delay: 30);
    var result = receive
    ['isAcceptItem'] ==
        '1'
        ? await deleteMaterialDetailOne({'id': value['id']})
        : await deleteMaterialDetailTwo({'id': value['id']});
    loading.dismiss();
    if (result != null&& result['hasError'] == null) {
      Fluttertoast.showToast(msg: '删除成功');
      page = 1;
      this.getAllReceived();
    }
    LogUtil.d(result);
  }

  /*
  * 发起审批
  * */
  sendAccept() async {
    loading.show(delay: 30);
    var result = await saveSubmitAccept({'requisitionAcceptId': receive['id']});
    loading.dismiss();
    if (result != null) {
      Fluttertoast.showToast(msg: '发起成功');
      bus.emit('refreshRequisitionList');
      bus.emit('refreshHome');
      Get.back();
    }
    LogUtil.d(result);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('领料单材料'),
        ),
        body: Container(
          color: Styles.MainBackgroundColor,
          padding: EdgeInsets.fromLTRB(
              0, 0, 0, MediaQuery.of(context).padding.bottom + 70),
          child: NotificationListener(
            onNotification: (_) {
              FocusScope.of(context).requestFocus(new FocusNode());
              return false;
            },
            child: EasyRefresh.custom(
                shrinkWrap: true,
                firstRefresh: true,
                controller: _controller,
                header: MaterialHeader(),
                footer: ClassicalFooter(
                    loadingText: '加载中',
                    loadText: '上拉加载',
                    noMoreText: '没有更多数据',
                    loadedText: '加载完成',
                    infoText: '更新于 %T',
                    textColor: Styles.NoMoreColor,
                    showInfo: false),
                emptyWidget: (dataSource.length == 0 && !firstLoad)
                    ? Center(
                        child: Image(
                          image: AssetImage('assets/images/no_data.png'),
                          width: 128,
                          height: 150,
                        ),
                      )
                    : null,
                onRefresh: () async {
                  _controller.finishLoad(success: true, noMore: false);
                  if (mounted) {
                    page = 1;
                    this.getAllReceived();
                  }
                },
                onLoad: () async {
                  await Future.delayed(Duration(seconds: 2), () {
                    if (mounted) {
                      page++;
                      this.getAllReceived();
                    }
                  });
                },
                slivers: <Widget>[
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        return Column(
                          children: [
                            GestureDetector(
                              onTap: () {
                                Get.toNamed(RouteConfig.materialRequisitionDetail,arguments: {'pass':this.dataSource[index],'detail':receive});
                              },
                              child: Container(
                                alignment: Alignment.centerLeft,
                                color: Colors.white,
                                margin:
                                EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                                padding: EdgeInsets.fromLTRB(
                                    Styles.spacing12,
                                    Styles.spacing8,
                                    Styles.spacing12,
                                    Styles.spacing8),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0, Styles.spacing4, 0, Styles.spacing4),
                                      child: Text(
                                        '规格型号  ${this.dataSource[index]['specName']}',
                                        style: TextStyle(
                                            color: Styles.DetailColor,
                                            fontSize: Styles.NormalFont),
                                      ),
                                    ),
                                    Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0, Styles.spacing4, 0, Styles.spacing4),
                                      child: Text(
                                        '材料类型  ${this.dataSource[index]['materialType'] == '1' ? '周转材料' : '非周转材料'}',
                                        style: TextStyle(
                                            color: Styles.DetailColor,
                                            fontSize: Styles.NormalFont),
                                      ),
                                    ),
                                    Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0, Styles.spacing4, 0, Styles.spacing4),
                                      child: Text(
                                        '数       量  ${this.dataSource[index]['requestQuantity'] != null ? this.dataSource[index]['requestQuantity']['value'] : '--'}',
                                        style: TextStyle(
                                            color: Styles.DetailColor,
                                            fontSize: Styles.NormalFont),
                                      ),
                                    ),
                                    Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0, Styles.spacing4, 0, Styles.spacing4),
                                      child: Text(
                                        '计量单位  ${this.dataSource[index]['measureUnit']}',
                                        style: TextStyle(
                                            color: Styles.DetailColor,
                                            fontSize: Styles.NormalFont),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            canEdit?GestureDetector(
                              onTap: () {
                                FocusScope.of(context).requestFocus(new FocusNode());
                                showDialog(
                                    barrierDismissible: false,
                                    context: this.context,
                                    builder:
                                        (BuildContext context) {
                                      return AlertDialog(
                                        title: Text('注意'),
                                        content: Text('确认删除吗？'),
                                        actions: <Widget>[
                                          new Container(
                                            child: FlatButton(
                                              child: new Text(
                                                "取消",
                                                style: TextStyle(
                                                    color: Colors
                                                        .black),
                                              ),
                                              onPressed: () {
                                                Navigator.pop(
                                                    context);
                                              },
                                            ),
                                          ),
                                          new Container(
                                            child: FlatButton(
                                              child: new Text(
                                                "确定",
                                                style: TextStyle(
                                                    color: Colors
                                                        .red),
                                              ),
                                              onPressed: () {
                                                Navigator.pop(
                                                    context);
                                                this.deleteMaterialDetail(
                                                    this.dataSource[index]);
                                              },
                                            ),
                                          ),
                                        ],
                                      );
                                    });

                              },
                              child: Container(
                                padding:
                                EdgeInsets.all(Styles.spacing16),
                                decoration: BoxDecoration(
                                    border: Border(top: BorderSide(color: Styles.LineColor,width: 1)),color: Colors.white),
                                alignment: Alignment.center,
                                child: Text(
                                  '删除',
                                  style: TextStyle(
                                      color: Styles.DetailColor,
                                      fontSize: Styles.NormalFont),
                                ),
                              ),
                            ):Container()
                          ],
                        );
                      },
                      childCount: dataSource.length,
                    ),
                  ),
                ]),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: canEdit?Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: receive['materialLevel'] == '1'
              ? Container(
                  decoration: new BoxDecoration(
                    border: Border.all(width: 1, color: Styles.BlueColor),
                    //背景
                    color: Styles.LightBlueColor,
                    //设置四周圆角 角度
                    borderRadius: BorderRadius.all(Radius.circular(12.0)),
                  ),
                  margin: EdgeInsets.fromLTRB(
                      Styles.spacing8, 0, Styles.spacing8, 0),
                  child: FlatButton(
                      onPressed: () {
                        Get.toNamed(
                            RouteConfig.addMaterialRequisitionDetail,
                            arguments: receive);
                      },
                      child: Container(
                        height: Styles.MainButtonHeight,
                        alignment: Alignment.center,
                        child: Text('添加材料',
                            style: TextStyle(
                                color: Styles.BlueColor,
                                fontSize: Styles.MainButtonTextFont)),
                      )),
                )
              : (receive
          ['isAcceptItem'] ==
              '1' &&
              receive
              ['recordEditFlag'] !=
                  2 &&
              receive
              ['recordEditFlag'] !=
                  3 &&
              receive
              ['wfProcInstId'] ==
                  null)
                  ? Row(
                      children: [
                        Expanded(
                            child: GestureDetector(
                          child: Container(
                            decoration: new BoxDecoration(
                              border:
                                  Border.all(width: 1, color: Styles.BlueColor),
                              //背景
                              color: Styles.LightBlueColor,
                              //设置四周圆角 角度
                              borderRadius:
                                  BorderRadius.all(Radius.circular(12.0)),
                            ),
                            margin: EdgeInsets.fromLTRB(
                                Styles.spacing8, 0, Styles.spacing8, 0),
                            child: FlatButton(
                                onPressed: () {
                                  Get.toNamed(
                                      RouteConfig.addMaterialRequisitionDetail,
                                      arguments: receive);
                                },
                                child: Container(
                                  height: Styles.MainButtonHeight,
                                  alignment: Alignment.center,
                                  child: Text('添加材料',
                                      style: TextStyle(
                                          color: Styles.BlueColor,
                                          fontSize: Styles.MainButtonTextFont)),
                                )),
                          ),
                        )),
                        Expanded(
                            child: Container(
                          decoration: new BoxDecoration(
                            //背景
                            color: Styles.BlueColor,
                            //设置四周圆角 角度
                            borderRadius:
                                BorderRadius.all(Radius.circular(12.0)),
                          ),
                          margin: EdgeInsets.fromLTRB(
                              Styles.spacing8, 0, Styles.spacing8, 0),
                          child: FlatButton(
                              onPressed: () {
                                FocusScope.of(context).requestFocus(new FocusNode());
                                showDialog(
                                    barrierDismissible: false,
                                    context: this.context,
                                    builder: (BuildContext context) {
                                      return AlertDialog(
                                        title: Text('注意'),
                                        content: Text('确认发起审批吗？'),
                                        actions: <Widget>[
                                          new Container(
                                            child: FlatButton(
                                              child: new Text(
                                                "取消",
                                                style: TextStyle(
                                                    color: Colors.black),
                                              ),
                                              onPressed: () {
                                                Navigator.pop(context);
                                              },
                                            ),
                                          ),
                                          new Container(
                                            child: FlatButton(
                                              child: new Text(
                                                "确定",
                                                style: TextStyle(
                                                    color: Colors.red),
                                              ),
                                              onPressed: () {
                                                Navigator.pop(context);
                                                this.sendAccept();
                                              },
                                            ),
                                          ),
                                        ],
                                      );
                                    });
                              },
                              child: Container(
                                height: Styles.MainButtonHeight,
                                alignment: Alignment.center,
                                child: Text('发起审批',
                                    style: TextStyle(
                                        color: Styles.WhiteGray,
                                        fontSize: Styles.MainButtonTextFont)),
                              )),
                        ))
                      ],
                    )
                  : GestureDetector(
                      child: Container(
                        decoration: new BoxDecoration(
                          border: Border.all(width: 1, color: Styles.BlueColor),
                          //背景
                          color: Styles.LightBlueColor,
                          //设置四周圆角 角度
                          borderRadius: BorderRadius.all(Radius.circular(12.0)),
                        ),
                        margin: EdgeInsets.fromLTRB(
                            Styles.spacing8, 0, Styles.spacing8, 0),
                        child: FlatButton(
                            onPressed: () {
                              Get.toNamed(
                                  RouteConfig.addMaterialRequisitionDetail,
                                  arguments: receive);
                            },
                            child: Container(
                              height: Styles.MainButtonHeight,
                              alignment: Alignment.center,
                              child: Text('添加材料',
                                  style: TextStyle(
                                      color: Styles.BlueColor,
                                      fontSize: Styles.MainButtonTextFont)),
                            )),
                      ),
                    ),
        ):Container());
  }
}
